package auction.synchronisation;

import java.util.ArrayList;

import auction.server.Server;

public class Groupbid extends Thread{
	private String bidder;

	private int id;
	private double amount;
	private Boolean confirmone =false;
	private Boolean confirmtwo =false;
	private String ret="";
	private int requests=0;
	private ArrayList<Groupbid> bids;
	private int time=0;
	public Groupbid(String bidder, int id, double amount,ArrayList<Groupbid> bids){
		this.bidder=bidder;
		this.id = id;
		this.amount = amount;
		this.bids = bids;
	}
	public void run(){

		while(time<20){
			synchronized(this){
				try {
					this.wait(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			time++;
		}
		requests=100;
		getbidAnswer();
	}
	//shutdown thread
	public void shutdown(){
		this.time=100;
	}
	public String getBidder() {
		return bidder;
	}
	public void setBidder(String bidder) {
		this.bidder = bidder;
	}
	public int getBidId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public double getAmaount() {
		return amount;
	}
	public void setAmaount(double amaount) {
		this.amount = amaount;
	}
	public synchronized void confirm(){
		synchronized(confirmone){
		  synchronized(confirmtwo){
				if(!confirmone){
					time =0;
					confirmone=true;
				}
				else{

					if(!confirmtwo){
						confirmtwo=true;
						time=20;
						ret = Server.bidAuction(bidder, id, amount,true);

					}

				}
		  }
		}
			
		

	}
	public synchronized String getbidAnswer(){
		if(requests>0){
			if(bids.contains(this)){
				bids.remove(this);
			}
		}
		else{
			requests++;
			
		}
		return ret;
	}
	public synchronized void resetFirsConfirmation(){

		if(confirmone){
			this.confirmone=false;
		}

	}
	public synchronized boolean isConfirmed(){
		//System.out.println(confirmone+ " " + confirmtwo);
		if(confirmone){
			if (confirmtwo){
				return true;
			}
		}
		return false;
	}

}
